package com.rtsapp.server.monitor;

import com.rtsapp.server.logger.Logger;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 监控线程
 */
public class MonitorThread implements Runnable{

    private static final Logger LOGGER =com.rtsapp.server.logger.LoggerFactory.getLogger( MonitorThread.class );


    private static final MonitorThread instance = new MonitorThread();
    private static boolean started = false;

    public static MonitorThread getInstance(){
        return instance;
    }

    /**
     * 启动监控线程
     */
    public synchronized  static void start(){
        if( started ){
            return;
        }

        Thread t = new Thread( getInstance() , "MonitorThread" );
        t.start();
        started = true;
    }

    /**
     * 停止监控线程
     */
    public synchronized static  void stop(){
        if( !started ){
            getInstance().stop = true ;
            started = false;
        }
    }


    private  final CopyOnWriteArrayList<IMonitorTask> threads = new CopyOnWriteArrayList<>();
    private boolean stop = false;

    /**
     * 加入一个监控
     * @param t
     */
    public void addMonitor( IMonitorTask t  ){
        if( t == null ){
            throw new IllegalArgumentException( "参数 IMonitorTask 不能为空" );
        }
        threads.add( t );
    }

    /**
     * 移除一个监控
     * @param t
     */
    public void removeMonitor( IMonitorTask t ){
        if( t == null ){
            throw new IllegalArgumentException( "参数 IMonitorTask 不能为空" );
        }
        threads.remove( t );
    }


    @Override
    public void run() {

        while( !stop ){

            Iterator<IMonitorTask> it =  threads.iterator();
            while( it.hasNext() ){
                IMonitorTask task = it.next();

                try {
                    task.monitor();
                }catch( Throwable ex ){
                    LOGGER.error("task.monitor()执行出错" + ex );
                }
            }

            try {
                //休眠1秒再来检测
                Thread.sleep( 1000 );
            } catch (InterruptedException e) {
                LOGGER.error( "MonitorThread执行中发生异常:" , e );
            }
        }

    }





}